package org.tc.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.tc.bean.Item;
import org.tc.bean.ItemDesc;
import org.tc.common.Result;
import org.tc.common.ResultUtils;
import org.tc.exception.CustomException;
import org.tc.service.ItemRpcService;
import org.tc.service.ItemService;
import org.tc.service.JedisService;
import org.tc.service.impl.ItemServiceImpl;


/**
 * Created by zxd on 2018/1/29.
 */
@RequestMapping("/item")
@Controller
public class ItemController {
  private Logger LOGGER= LoggerFactory.getLogger(ItemController.class);


    @Autowired
    private ItemService itemService;
    

    @Autowired
    private JedisService jedisService;

    @RequestMapping(value = "/{itemId}",method = RequestMethod.GET)
    public String toItem(Model model,@PathVariable("itemId") Long itemId)
            throws CustomException {
        LOGGER.debug("查询的商品基本信息的id是{},",itemId);
        //查询商品的数据
       Item  item=itemService.queryItemById(itemId);


        ItemDesc itemDesc = itemService.queryItemDescById(itemId);
        if(item==null||itemDesc==null){
           new CustomException("查询的商品不存在");
           LOGGER.error("查询的商品不存在{}",itemId);
       }
        //放到model里面
        model.addAttribute("item",item);

        model.addAttribute("itemDesc",itemDesc);
        String image = item.getImage();
        if(image==null||image.equals("")){
            new CustomException("商品图片不存在，请联系管理员!");
            LOGGER.error("商品的图片不存在，itemId is {}",itemId);
        }
        String[] images = image.split(",");
        model.addAttribute("images",images);
        return "item";
    }

    @RequestMapping(value = "/cache/delete/{itemId}")
    @ResponseBody
    public Result deleteCache(@PathVariable("itemId") Long itemId){
        //移到servcie
        jedisService.del(ItemServiceImpl.ITEM_CACHE + itemId);
        LOGGER.info("移除商品{}的缓存",itemId);
        return ResultUtils.buildSuccess();
    }


}
